package com.rxsk.cas.token;

import com.rxsk.cas.component.JwtTokenUtil;
import com.rxsk.cas.exception.JwtTokenException;
import com.rxsk.cas.pojo.UserDetailPlus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @Deacription AbstractToken
 */
public class AbstractToken {

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 生成token
     * @param userDetails 用户信息
     * @param expireTime 有效时长，单位：秒
     * @return
     */
    public String create(UserDetailPlus userDetails, long expireTime) {
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new JwtTokenException("UserToken entity is empty");
        }
        String userName = userDetails.getUsername();
        if(StringUtils.isBlank(userName)){
            throw new JwtTokenException("UserToken userName is empty");
        }
        return jwtTokenUtil.generateToken(userDetails,expireTime);
    }


    /**
     * 生成redis key
     * @param userDetails 用户信息
     * @return
     */
    public String buildKey(UserDetailPlus userDetails){
        if (ObjectUtils.isEmpty(userDetails)) {
            throw new JwtTokenException("UserDetails entity is empty");
        }
        String userName = userDetails.getUsername();
        if (ObjectUtils.isEmpty(userName)) {
            throw new JwtTokenException("UserDetails userName is empty");
        }
        return jwtTokenUtil.buildRedisKey(userDetails);
    }
}
